package com.texplose.runner;

import com.texplose.entity.Recipe;
import com.texplose.entity.constant.SystemConstants;
import com.texplose.mapper.RecipeMapper;
import com.texplose.util.RedisCache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : lyj
 * @Timer : 2022/5/24
 * @Description :
 * 在springboot启动前将数据库中recipe表views字段添加到redis中
 */
@Component
public class ViewCounterRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private RecipeMapper recipeMapper;

    @Autowired
    private RedisCache redisCache;


    @Override
    public void run(String... args) throws Exception {
        logger.info("ViewCounterRunner..........");
        List<Recipe> recipeList =  recipeMapper.selectList();
        Map<String , Integer> map =
                recipeList.stream()
                        .collect(Collectors.toMap( recipe -> String.valueOf(recipe.getId()), recipe -> {
            return recipe.getViews();
        }));

        redisCache.setCacheMap(SystemConstants.REDIS__VIEWS_MAP,map);

    }
}
